package weibo.model;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.Vector;

import net.rim.device.api.i18n.SimpleDateFormat;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

import code.Function;

import weibo.http.Response;

public class Status extends WeiboResponse
{
	private User user = null;                            //作者信息
	private Date createdAt;                              //status创建时间
	private String id;                                   //status id
	private String mid;                                  //微博MID
	private long idstr;                                  //保留字段，请勿使用                     
	private String text;                                 //微博内容
	private Source source;                               //微博来源
	private boolean favorited;                           //是否已收藏
	private boolean truncated;							 //是否已截断
	//private long inReplyToStatusId;                      //回复ID，暂未支持
	//private long inReplyToUserId;                        //回复人ID，暂未支持
	//private String inReplyToScreenName;                  //回复人昵称，暂未支持
	private String thumbnailPic;                         //微博内容中的图片的缩略地址
	private String bmiddlePic;                           //中型图片
	private String originalPic;                          //原始图片
	private Status retweetedStatus;               //转发的博文，内容为status，如果不是转发，则没有此字段
	private String geo;                                  //地理信息，保存经纬度，没有时不返回此字段
	private double latitude = -1;                        //纬度
	private double longitude = -1;                       //经度
	private int repostsCount;                            //转发数
	private int commentsCount;                           //评论数
	private PictureUrls pic_urls=null;					 //微博配图
	//private String annotations;                        //元数据，没有时不返回此字段，暂未支持
	//private int mlevel;								 //暂未支持
	private Visible visible;
	private String deleted;
	
	public Status() {}
	
	public Status(Response res)throws WeiboException
	{
		super(res);
		JSONObject json=res.asJSONObject();
		constructJson(json);
	}

	private void constructJson(JSONObject json) throws WeiboException 
	{
		try
		{
			createdAt =parseDate(json.getString("created_at"));
			id = json.getString("id");
			mid=json.getString("mid");
			idstr = json.getLong("idstr");
			text = json.getString("text");
			deleted=json.optString("deleted");
			if(deleted.equals("1")) {return;}
			
			if(!json.isNull("source")){source = new Source(json.getString("source"));}
			//inReplyToStatusId = getLong("in_reply_to_status_id", json);
			//inReplyToUserId = getLong("in_reply_to_user_id", json);
			//inReplyToScreenName=json.getString("in_reply_to_screen_name");
			favorited = getBoolean("favorited", json);
			truncated = getBoolean("truncated", json);
			thumbnailPic = json.optString("thumbnail_pic");
			bmiddlePic = json.optString("bmiddle_pic");
			originalPic = json.optString("original_pic");
			repostsCount = json.getInt("reposts_count");
			commentsCount = json.getInt("comments_count");
			//annotations = json.getString("annotations");
			if(!json.isNull("user")) {user = new User(json.getJSONObject("user"));}
			if(!json.isNull("retweeted_status")){retweetedStatus= new Status(json.getJSONObject("retweeted_status"));}
			//mlevel = json.getInt("mlevel");
			//geo= json.getString("geo");
			//if(geo!=null &&!"".equals(geo) &&!"null".equals(geo)){getGeoInfo(geo);}
			if(!json.isNull("visible"))
			{
				visible= new Visible(json.getJSONObject("visible"));
				visible.toString();
			}
			if(!json.isNull("pic_urls")) {pic_urls=new PictureUrls(json.getJSONArray("pic_urls"));}
		} catch (JSONException je) {
			throw new WeiboException(je.getMessage() + ":" + json.toString());
		}
	}

/*	
	private void getGeoInfo(String geo) {
		StringBuffer value= new StringBuffer();
		//for(char c:geo.toCharArray()){
		for(int i=0; i<geo.toCharArray().length; i++)
		{
			char c=geo.toCharArray()[i];
			if(c>45&&c<58){value.append(c);}
			if(c==44)
			{
				if(value.length()>0)
				{
					latitude=Double.parseDouble(value.toString());
					value.delete(0, value.length());
				}
			}
		}
		
		longitude=Double.parseDouble(value.toString());
	}
*/
	
	public Status(JSONObject json)throws WeiboException, JSONException
	{
		constructJson(json);
	}
	
	public Status(String str) throws WeiboException, JSONException
	{
		super();
		JSONObject json = new JSONObject(str);
		constructJson(json);
	}

	public boolean isDeleted() {return deleted.equals("1") ? true : false;}
	public User getUser() {return user;}
	public long getIdstr() {return idstr;}
	
	public String getCreatedAtLong()
	{
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		return sdf.formatLocal(createdAt.getTime());
	}

	public String getCreatedAtShort()
	{
		String formatString="M/d HH:mm";
		Calendar calendarToday=Calendar.getInstance(TimeZone.getDefault());
		Calendar calendarCreate=Calendar.getInstance(TimeZone.getDefault());
		
		calendarToday.setTime(new Date(System.currentTimeMillis()));
		calendarCreate.setTime(createdAt);
		
		calendarToday.set(Calendar.HOUR_OF_DAY, 0);
		calendarCreate.set(Calendar.HOUR_OF_DAY, 0);
		calendarToday.set(Calendar.MINUTE, 0);
		calendarCreate.set(Calendar.MINUTE, 0);
		calendarToday.set(Calendar.SECOND, 0);
		calendarCreate.set(Calendar.SECOND, 0);
		calendarToday.set(Calendar.MILLISECOND, 1);
		calendarCreate.set(Calendar.MILLISECOND, 1);
		
		int todayYear=calendarToday.get(Calendar.YEAR);
		int createYear=calendarCreate.get(Calendar.YEAR);
		int todayMonth=calendarToday.get(Calendar.MONTH);
		int createMonth=calendarCreate.get(Calendar.MONTH);
		int todayDay=calendarToday.get(Calendar.DAY_OF_MONTH);
		int createDay=calendarCreate.get(Calendar.DAY_OF_MONTH);

		if((todayYear-createYear)>=1)
		{
			formatString="yyyy/M/d HH:mm";
		} else if((todayMonth==createMonth) && todayDay==createDay)
		{
			formatString="HH:mm";
		}
		
		SimpleDateFormat sdf=new SimpleDateFormat(formatString);
		
		return sdf.formatLocal(createdAt.getTime());
	}

	public String getId() {return id;}
	public String getText() {return text;}
	public Source getSource() {return source;}
	public boolean isFavorited() {return favorited;}
	//public long getInReplyToStatusId() {return inReplyToStatusId;}
	//public long getInReplyToUserId() {return inReplyToUserId;}
	//public String getInReplyToScreenName() {return inReplyToScreenName;}
	public String getThumbnailPic() {return thumbnailPic;}
	public String getBmiddlePic() {return bmiddlePic;}
	public String getOriginalPic() {return originalPic;}
	public Status getRetweetedStatus() {return retweetedStatus;}
	public String getGeo() {return geo;}
	public double getLatitude() {return latitude;}
	public double getLongitude() {return longitude;}
	public int getRepostsCount() {return repostsCount;}
	public int getCommentsCount() {return commentsCount;}
	public String getMid() {return mid;}	
	//public String getAnnotations() {return annotations;}
	//public int getMlevel() {return mlevel;}
	public Visible getVisible() {return visible;}
	public boolean isTruncated() {return truncated;}
	public String[] getThumbnailImages() {return pic_urls.getThumbnailPics();}
	public PictureUrls getPicUrls() {return pic_urls;}
	
	public void setUser(User user) {this.user = user;}
	public void setIdstr(long idstr) {this.idstr = idstr;}
	public void setCreatedAt(Date createdAt) {this.createdAt = createdAt;}
	public void setId(String id) {this.id = id;}
	public void setText(String text) {this.text = text;}
	public void setSource(Source source) {this.source = source;}
	public void setFavorited(boolean favorited) {this.favorited = favorited;}
	//public void setInReplyToStatusId(long inReplyToStatusId) {this.inReplyToStatusId = inReplyToStatusId;}
	//public void setInReplyToUserId(long inReplyToUserId) {this.inReplyToUserId = inReplyToUserId;}
	//public void setInReplyToScreenName(String inReplyToScreenName) {this.inReplyToScreenName = inReplyToScreenName;}
	public void setThumbnailPic(String thumbnailPic) {this.thumbnailPic = thumbnailPic;}
	public void setBmiddlePic(String bmiddlePic) {this.bmiddlePic = bmiddlePic;}
	public void setOriginalPic(String originalPic) {this.originalPic = originalPic;}
	public void setRetweetedStatus(Status retweetedStatus) {this.retweetedStatus = retweetedStatus;}
	public void setGeo(String geo) {this.geo = geo;}
	public void setLatitude(double latitude) {this.latitude = latitude;}
	public void setLongitude(double longitude) {this.longitude = longitude;}
	public void setRepostsCount(int repostsCount) {this.repostsCount = repostsCount;}
	public void setCommentsCount(int commentsCount) {this.commentsCount = commentsCount;}
	public void setMid(String mid) {this.mid = mid;}
	//public void setAnnotations(String annotations) {this.annotations = annotations;}
	//public void setMlevel(int mlevel) {this.mlevel = mlevel;}
	public void setVisible(Visible visible) {this.visible = visible;}
	public void setTruncated(boolean truncated) {this.truncated = truncated;}
	
	public static StatusWapper constructWapperStatus(Response res) throws WeiboException
	{
		JSONError error=new JSONError(res.asString());
		if(error.getErrorCode()!=0) {Function.errorDialog(error.toString()); return new StatusWapper(new Vector());}
		
		JSONObject jsonStatus = res.asJSONObject(); //asJSONArray();
		JSONArray statuses = null;
		try {
			if(!jsonStatus.isNull("statuses"))
			{				
				statuses = jsonStatus.getJSONArray("statuses");
			}
			
			if(!jsonStatus.isNull("reposts"))
			{
				statuses = jsonStatus.getJSONArray("reposts");
			}
			
			int size = statuses.length();
			Vector status = new Vector(size);
			
			for (int i = 0; i < size; i++)
			{
				status.addElement(new Status(statuses.getJSONObject(i)));
			}
			//long previousCursor = jsonStatus.getLong("previous_curosr");
			//long nextCursor = jsonStatus.getLong("next_cursor");
			//long totalNumber = jsonStatus.getLong("total_number");
			//String hasvisible = jsonStatus.getString("hasvisible");
			return new StatusWapper(status);//, previousCursor, nextCursor,totalNumber,hasvisible);
		} catch (JSONException jsone) {throw new WeiboException(jsone.toString());}
	}

	public int hashCode()
	{
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	public boolean equals(Object obj)
	{
		if (this == obj) return true;
		if (obj == null) return false;
		if (getClass() != obj.getClass()) return false;
		
		Status other = (Status) obj;
		if (id == null)
		{
			if (other.id != null) return false;
		} else if (!id.equals(other.id)) return false;
		
		return true;
	}

	public String toString() {
		return "\n\u2605Status [" +
			   //"\n\u2022 user=" + user +
			   "\n\u2022 idstr=" + idstr +
			   "\n\u2022 createdAt=" + createdAt +
			   "\n\u2022 id=" + id + 
			   "\n\u2022 text=" + text + 
			   "\n\u2022 source=" + source + 
			   "\n\u2022 favorited=" + favorited + 
			   "\n\u2022 truncated=" + truncated + 
			   //"\n\u2022 inReplyToStatusId=" + inReplyToStatusId +
			   //"\n\u2022 inReplyToUserId=" + inReplyToUserId +
			   //"\n\u2022 inReplyToScreenName=" + inReplyToScreenName +
			   "\n\u2022 retweetedStatus=" + retweetedStatus + 
			   "\n\u2022 geo=" + geo +
			   "\n\u2022 latitude=" + latitude + 
			   "\n\u2022 longitude=" + longitude +
			   "\n\u2022 repostsCount=" + repostsCount + 
			   "\n\u2022 commentsCount=" + commentsCount + 
			   "\n\u2022 mid=" + mid +
			   //"\n\u2022 mlevel=" + mlevel +
			   "\n\u2022 visible=" + visible + 
			   "\n\u2022]";
	}
}